package com.wrench.elevator.base.user.service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wrench.elevator.base.user.dao.ChengtiDao;
import com.wrench.elevator.base.user.domain.Chengti;
import com.wrench.elevator.base.user.domain.Face;
import com.wrench.elevator.base.user.domain.Person;
import com.wrench.elevator.constant.Dict;
import com.wrench.elevator.constant.Result;
import com.wrench.elevator.exception.WrenchException;
import com.wrench.elevator.util.WrenchUtil;

/**
 * @Description: ChengtiService
 * @author yangchenfeng
 * @date Oct 24, 2017 3:49:01 PM
 * @version V1.0
 */
@Component
public class ChengtiService
{
    
    private static final Logger logger = LoggerFactory.getLogger(ChengtiService.class);
    
    @Resource
    private ChengtiDao dao;
    
    @Resource
    private FaceService faceService;
    
    @Resource
    private ConsumeService consumeService;
    
    @Resource
    private PersonService personService;
    
    /**
     * 人脸识别乘梯
     * */
    public void chengti(String face_id)
        throws WrenchException
    {
        if (WrenchUtil.hasNull(face_id))
        {
            logger.error("==> param is not found , face_id = {} ", face_id);
            throw new WrenchException(Result.PARAM_NOT_FOUND_CODE, Result.PARAM_NOT_FOUND_MESSAGE);
        }
        
        if (!WrenchUtil.isInt(face_id))
        {
            logger.error("==> string is not int type , face_id = {} ", face_id);
            throw new WrenchException(Result.STRING_IS_NOT_INT_CODE, Result.STRING_IS_NOT_INT_MESSAGE);
        }
        
        Face face = faceService.getFaceByFaceId(face_id);
        String user_id = String.valueOf(face.getUser_id());
        String face_id_identity =
            "{\"face_id\":\"" + face_id + "\",\"identity\":\"" + face.getIdentity() + "\",\"user_id\":\""
                + face.getUser_id() + "\"}";
        WrenchUtil.cacheChengti(user_id, face_id_identity);
        logger.debug("==> WrenchUtil.cacheChengti(user_id, face_id_identity) execute success , user_id = {} , face_id_identity = {}",
            user_id,
            face_id_identity);
    }
    
    /**
     * 人脸识别乘梯 云接口
     * 
     * @throws WrenchException
     * */
    public void chengtiCloud(String person_id)
        throws WrenchException
    {
        if (WrenchUtil.hasNull(person_id))
        {
            logger.error("==> param is not found , person_id = {} ", person_id);
            throw new WrenchException(Result.PARAM_NOT_FOUND_CODE, Result.PARAM_NOT_FOUND_MESSAGE);
        }
        
        Person person = null;
        person = personService.getPerson(person_id);
        
        if (WrenchUtil.hasNull(person))
        {
            logger.error("==> person_id is not found , person_id = {} , person = {}", person_id, person);
            throw new WrenchException(Result.PERSON_NOT_FOUND_PERSON_ID_CODE, Result.PERSON_NOT_FOUND_PERSON_ID_MESSAGE);
        }
        
        int user_id = person.getUser_id();
        String identity = person.getIdentity();
        String person_id_identity =
            "{\"person_id\":\"" + person_id + "\",\"identity\":\"" + identity + "\",\"user_id\":\"" + user_id + "\"}";
        WrenchUtil.cacheChengti(String.valueOf(user_id), person_id_identity);
        logger.debug("==> WrenchUtil.cacheChengti(user_id, person_id_identity) execute success , user_id = {} , person_id_identity = {}",
            user_id,
            person_id_identity);
        
    }
    
    /**
     * 手动button呼梯 云
     * */
    public void hutiCloud(String user_id)
        throws WrenchException
    {
        if (WrenchUtil.hasNull(user_id))
        {
            logger.error("==> param is not found , user_id = {} ", user_id);
            throw new WrenchException(Result.PARAM_NOT_FOUND_CODE, Result.PARAM_NOT_FOUND_MESSAGE);
        }
        
        if (!WrenchUtil.isInt(user_id))
        {
            logger.error("==> string is not int type , user_id = {} ", user_id);
            throw new WrenchException(Result.STRING_IS_NOT_INT_CODE, Result.STRING_IS_NOT_INT_MESSAGE);
        }
        
        String person_id_identity =
            "{\"user_id\":\"" + user_id + "\",\"person_id\":\"-999\",\"identity\":\"" + Dict.CHENGTI_IDENTITY_HUTI
                + "\"}";
        WrenchUtil.cacheChengti(user_id, person_id_identity);
        logger.debug("==> WrenchUtil.cacheChengti(user_id, face_id_identity) execute success , user_id = {} , person_id_identity = {}",
            user_id,
            person_id_identity);
    }
    
    /**
     * 手动button呼梯
     * */
    public void huti(String user_id)
        throws WrenchException
    {
        if (WrenchUtil.hasNull(user_id))
        {
            logger.error("==> param is not found , user_id = {} ", user_id);
            throw new WrenchException(Result.PARAM_NOT_FOUND_CODE, Result.PARAM_NOT_FOUND_MESSAGE);
        }
        
        if (!WrenchUtil.isInt(user_id))
        {
            logger.error("==> string is not int type , user_id = {} ", user_id);
            throw new WrenchException(Result.STRING_IS_NOT_INT_CODE, Result.STRING_IS_NOT_INT_MESSAGE);
        }
        
        String face_id_identity =
            "{\"user_id\":\"" + user_id + "\",\"face_id\":\"-999\",\"identity\":\"" + Dict.CHENGTI_IDENTITY_HUTI
                + "\"}";
        WrenchUtil.cacheChengti(user_id, face_id_identity);
        logger.debug("==> WrenchUtil.cacheChengti(user_id, face_id_identity) execute success , user_id = {} , face_id_identity = {}",
            user_id,
            face_id_identity);
    }
    
    /**
     * 添加乘梯记录
     * */
    @Transactional(rollbackFor = WrenchException.class)
    public int addChengti(Set<String> face_id_identitys)
        throws WrenchException
    {
        if (WrenchUtil.hasNull(face_id_identitys))
        {
            logger.error("==> param is not found  , face_id_identitys = {}  ", face_id_identitys);
            throw new WrenchException(Result.PARAM_NOT_FOUND_CODE, Result.PARAM_NOT_FOUND_MESSAGE);
        }
        
        String[] faceIdAndIdentity = getFaceIdAndIdentity(face_id_identitys);
        String identity = faceIdAndIdentity[2];
        String chengtirens_face_id = faceIdAndIdentity[1];
        String user_id = faceIdAndIdentity[0];
        String chengti_flow_no = WrenchUtil.getFlowNo(Dict.FLOW_NO_HEAD_CT);
        String chengti_time = WrenchUtil.nowTime();
        double consume_money = Dict.price;
        String status = Dict.CHENGTI_STATUS_DAIKOUKUAN;
        Chengti chengti = new Chengti();
        chengti.setChengti_flow_no(chengti_flow_no);
        chengti.setChengti_time(chengti_time);
        chengti.setChengtirens_face_id(chengtirens_face_id);
        chengti.setConsume_money(consume_money);
        chengti.setStatus(status);
        chengti.setUser_id(Integer.valueOf(user_id));
        chengti.setIdentity(identity);
        
        String consume_type = Dict.CONSUME_TYPE_CT;
        if (WrenchUtil.stringEquals(identity, "{\"HT\"}"))
        {
            consume_type = Dict.CONSUME_TYPE_HT;
        }
        
        consumeService.addConsume(String.valueOf(user_id), String.valueOf(consume_money), consume_type);
        
        int commit = -1;
        try
        {
            commit = dao.addChengti(chengti);
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            logger.error("==> commit = dao.addChengti(chengti) execute error , chengti  = {} , error = {}; ",
                chengti,
                e);
            throw new WrenchException(Result.DB_INSERT_ERROR_CODE, Result.DB_INSERT_ERROR_MESSAGE);
        }
        
        if (commit <= 0)
        {
            logger.error("==> commit = dao.addChengti(chengti) execute success , but commit <=0 , commit = {} , chengti = {} ",
                commit,
                chengti);
            throw new WrenchException(Result.CONSUME_ADD_CONSUME_FAIL_CODE, Result.CONSUME_ADD_CONSUME_FAIL_MESSAGE);
        }
        
        logger.debug("==> commit = dao.addChengti(chengti) execute success , commit = {} , chengti = {} ",
            commit,
            chengti);
        
        return commit;
    }
    
    
    
  /**
    * 添加乘梯记录
    * */
   @Transactional(rollbackFor = WrenchException.class)
   public int addChengtiCloud(Set<String> person_id_identitys)
       throws WrenchException
   {
       if (WrenchUtil.hasNull(person_id_identitys))
       {
           logger.error("==> param is not found  , person_id_identitys = {}  ", person_id_identitys);
           throw new WrenchException(Result.PARAM_NOT_FOUND_CODE, Result.PARAM_NOT_FOUND_MESSAGE);
       }
       
       String[] personIdAndIdentity = getPersonIdAndIdentityCloud(person_id_identitys);
       
       logger.debug("========================================================================>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
       logger.debug("personIdAndIdentity====>"+Arrays.toString(personIdAndIdentity));
       
       String identity = personIdAndIdentity[2];
       String chengtirens_person_id = personIdAndIdentity[1];
       String user_id = personIdAndIdentity[0];
       String chengti_flow_no = WrenchUtil.getFlowNo(Dict.FLOW_NO_HEAD_CT);
       String chengti_time = WrenchUtil.nowTime();
       double consume_money = Dict.price;
       String status = Dict.CHENGTI_STATUS_DAIKOUKUAN;
       Chengti chengti = new Chengti();
       chengti.setChengti_flow_no(chengti_flow_no);
       chengti.setChengti_time(chengti_time);
      // chengti.setChengtirens_face_id(chengtirens_face_id);
       chengti.setChengtirens_person_id(chengtirens_person_id);
       chengti.setConsume_money(consume_money);
       chengti.setStatus(status);
       chengti.setUser_id(Integer.valueOf(user_id));
       chengti.setIdentity(identity);
       
       String consume_type = Dict.CONSUME_TYPE_CT;
       if (WrenchUtil.stringEquals(identity, "{\"HT\"}"))
       {
           consume_type = Dict.CONSUME_TYPE_HT;
       }
       
       consumeService.addConsume(String.valueOf(user_id), String.valueOf(consume_money), consume_type);
       
       int commit = -1;
       try
       {
           commit = dao.addChengti(chengti);
       }
       catch (Exception e)
       {
           // TODO Auto-generated catch block
           logger.error("==> commit = dao.addChengti(chengti) execute error , chengti  = {} , error = {}; ",
               chengti,
               e);
           throw new WrenchException(Result.DB_INSERT_ERROR_CODE, Result.DB_INSERT_ERROR_MESSAGE);
       }
       
       if (commit <= 0)
       {
           logger.error("==> commit = dao.addChengti(chengti) execute success , but commit <=0 , commit = {} , chengti = {} ",
               commit,
               chengti);
           throw new WrenchException(Result.CONSUME_ADD_CONSUME_FAIL_CODE, Result.CONSUME_ADD_CONSUME_FAIL_MESSAGE);
       }
       
       logger.debug("==> commit = dao.addChengti(chengti) execute success , commit = {} , chengti = {} ",
           commit,
           chengti);
       
       return commit;
   }
    
    private String[] getFaceIdAndIdentity(Set<String> face_id_identitys)
    {
        String[] faceIdAndIdentity = new String[3];
        
        Set<String> faceIds = new HashSet<>();
        Set<String> identitys = new HashSet<>();
        JSONObject jo = null;
        for (String face_id_identity : face_id_identitys)
        {
            jo = JSON.parseObject(face_id_identity);
            int face_id = jo.getIntValue("face_id");
            String identity = jo.getString("identity");
            if (face_id > 0)
            {
                faceIds.add(String.valueOf(face_id));
            }
            identitys.add(identity);
            faceIdAndIdentity[0] = jo.getString("user_id");
        }
        faceIdAndIdentity[1] = JSON.toJSONString(faceIds);
        faceIdAndIdentity[2] = JSON.toJSONString(identitys);
        return faceIdAndIdentity;
        
    }
    
    private String[] getPersonIdAndIdentityCloud(Set<String> person_id_identitys)
    {
        String[] personIdAndIdentity = new String[3];
        
        Set<String> personIds = new HashSet<>();
        Set<String> identitys = new HashSet<>();
        JSONObject jo = null;
        for (String person_id_identity : person_id_identitys)
        {
            jo = JSON.parseObject(person_id_identity);
            String person_id = jo.getString("person_id");
            String identity = jo.getString("identity");
            if (!"-999".equals(person_id))
            {
                personIds.add(person_id);
            }
            
            identitys.add(identity);
            personIdAndIdentity[0] = jo.getString("user_id");
        }
        logger.debug("============================================****************************************************>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        logger.debug("JSON.toJSONString(personIds):"+JSON.toJSONString(personIds));
        logger.debug("(personIds).size():"+(personIds).size());
        logger.debug("JSON.toJSONString(identitys):"+JSON.toJSONString(identitys));
        logger.debug("(identitys).size():"+(identitys).size());
        logger.debug("personIdAndIdentity[0]");
        personIdAndIdentity[1] = JSON.toJSONString(personIds);
        personIdAndIdentity[2] = JSON.toJSONString(identitys);
        return personIdAndIdentity;
        
    }
    
}
